using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IGridBallReloader
{
  public struct Request
  {
    public FieldModel fieldModel;
    public int[] lackOfBall;
  }

  public abstract class Mono : MonoBehaviour, IGridBallReloader
  {
    public abstract void HandleRequest(Request request);
  }

  public void HandleRequest(Request request);

}


public class GridBallReloader : IGridBallReloader.Mono
{
  private BagModel m_bagModel;

  public void SetBagModel(BagModel bagModel) {
    m_bagModel = bagModel;
  }

  public override void HandleRequest(IGridBallReloader.Request request) {
    var field = request.fieldModel;
    var grid = field.gridModel;
    for (int i = 0; i < request.lackOfBall.Length; i++)
    {
      FillColumnFromTop(grid, i, request.lackOfBall[i]);
    }
  }

  public void FillColumnFromTop(FieldModel.GridModel grid, int colunmIdx, int count) {
    var size = grid.size;
    for (int i = 0; i < count; i++)
    {
      var randomBall = m_bagModel.GetNotEmptyEntryRandomly();
      if (!randomBall.isValid || m_bagModel.TryConsume(randomBall.id, 1) > 0)
      {
        // reload once , if result still is Invalid , it will skip at next if
        m_bagModel.ReloadBag();
        randomBall = m_bagModel.GetNotEmptyEntryRandomly();
      }

      if (randomBall.isValid && m_bagModel.TryConsume(randomBall.id, 1) == 0)
      {
        var position = new Vector2Int(colunmIdx, size.y - 1 - i);
        grid.CreateBallModelAt(BallInfo.Create(randomBall.id), position);
      }
    }
  }
}
